"""
File   : 03_response_format_pydantic.py
Desc   : 结构化输出 response_format——Object Schema (使用 Pydantic)
Date   : 2024/11/27
Author : Tianyu Chen
"""

from pydantic import BaseModel
from openai import OpenAI

client = OpenAI()

class CalendarEvent(BaseModel):
    name: str
    date: str
    participants: list[str]

# You tried to pass a `BaseModel` class to `chat.completions.create()`; You must use `beta.chat.completions.parse()` instead
completion = client.beta.chat.completions.parse(
    model="gpt-4o-2024-08-06",
    messages=[
        {"role": "system", "content": "Extract the event information."},
        {"role": "user", "content": "Alice and Bob are going to a science fair on Friday."},
    ],
    response_format=CalendarEvent
    # 不支持流式输出
)

content = completion.choices[0].message.content
print(content)
""" output:
{"date":"Friday","name":"Science Fair","participants":["Alice","Bob"]}
"""

# event = completion.choices[0].message.parsed
# print(event)
""" output:
name='Science Fair' date='Friday' participants=['Alice', 'Bob']
"""

# print(completion)
""" output:
ParsedChatCompletion[CalendarEvent](
    id='chatcmpl-AQDyOrqCoxLEua9iMMs40dAJNPbIL', 
    choices=[
        ParsedChoice[CalendarEvent](
            finish_reason='stop', 
            index=0, 
            logprobs=None, 
            message=ParsedChatCompletionMessage[CalendarEvent](
                content='{"date":"2023-10-20","name":"Science Fair","participants":["Alice","Bob"]}', 
                refusal=None, 
                role='assistant', 
                audio=None, 
                function_call=None, 
                tool_calls=[], 
                parsed=CalendarEvent(name='Science Fair', date='2023-10-20', participants=['Alice', 'Bob'])
            )
        )
    ], 
    created=1730813604, 
    model='gpt-4o-2024-08-06', 
    object='chat.completion', 
    service_tier=None, 
    system_fingerprint='fp_159d8341cc', 
    usage=CompletionUsage(
        completion_tokens=22, 
        prompt_tokens=92, 
        total_tokens=114, 
        completion_tokens_details=CompletionTokensDetails(
            audio_tokens=None, 
            reasoning_tokens=0
        ), 
        prompt_tokens_details=PromptTokensDetails(
            audio_tokens=None, 
            cached_tokens=0
        )
    )
)
"""
